package cn.edu.ctbu.sbadmin.grade.service.impl;

import cn.edu.ctbu.sbadmin.common.core.AbstractService;
import cn.edu.ctbu.sbadmin.common.utils.MD5Utils;
import cn.edu.ctbu.sbadmin.grade.dao.StudentDao;
import cn.edu.ctbu.sbadmin.grade.domain.StudentDO;
import cn.edu.ctbu.sbadmin.grade.domain.SubjectDO;
import cn.edu.ctbu.sbadmin.grade.service.StudentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;

@Transactional
@Service
public class StudentServiceImpl extends AbstractService<StudentDao, StudentDO> implements StudentService {

    @Autowired
    StudentDao studentDao;
    /**
     * 通过userName查询用户信息
     * @param userName
     * @return
     */
    @Override
    public List<StudentDO> getByUserName(String userName){
        QueryWrapper<SubjectDO> studentDOQueryWrapper = new QueryWrapper<>();//新建一个查询
        studentDOQueryWrapper.eq("s_no",userName);//通过s_no查询
        List<StudentDO> studentDOList = studentDao.get(studentDOQueryWrapper);
        return studentDOList;
    }

    /**
     * 通过查询到的用户信息获取其密码
     * @param id
     * @return
     */
    @Override
    public String getPassword(Long id) {
        StudentDO studentDO = super.getById(id);//通过父类的getById方法获取StudentDO
        if (studentDO != null)
        {
            return studentDO.getPassword();//非空则返回密码
        } else {
            return "";
        }
    }
    @Override
    public Integer BatchInsertList(List<StudentDO> list) {
        Integer success_index = 0;

        //1依次读取pageList中的数据
        for (StudentDO item: list) {
            //2根据学号判断数据是否已经存在
            List<StudentDO> s_nos = this.findByAttrName("s_no", item.getUsername());
            if(s_nos.size()>0){
                //已经有数据，需要写错误日志和进行进一步和处理


            }else{
                //3如果不存在，则去需要进行插入处理
                //默认的密码就是学号
                item.setPassword(MD5Utils.encrypt(item.getUsername(), item.getUsername()));   //对用户的密码在客户端进行MD5加密
                item.setGmtCreate(new Date());
                item.setIsDeleted(0);

                //返回结果
                this.save(item);
                success_index++;
            }
        }

        return success_index;
    }
}

